package com.gitee.l0km.codegen.thrift.metadata;

import com.gitee.l0km.codegen.annotations.CodegenLength;
import com.gitee.l0km.xthrift.base.metadata.DecoratorThriftFieldMetadata;
import com.gitee.l0km.xthrift.base.metadata.ErpcProtocolType;
import com.gitee.l0km.xthrift.base.metadata.ThriftFieldMetadataUtil;
import com.google.common.base.Function;

public class CodegenPreAllocSizeGetter implements Function<DecoratorThriftFieldMetadata, Integer> {
	public static final CodegenPreAllocSizeGetter PREALLOC_SIZE_GETTER = new CodegenPreAllocSizeGetter(); 
	public CodegenPreAllocSizeGetter() {
	}

	@Override
	public Integer apply(DecoratorThriftFieldMetadata input) {
		 CodegenLength ann = ThriftFieldMetadataUtil.extractFieldAnnotation(input,CodegenLength.class);
		if(ann != null){
			if(!ann.prealloc()){
				return -1;
			}
			int limit;
			if(ann.value() > 0){
				limit = ann.value();
			}else if(ann.max() > 0){
				limit = ann.max();
			} else{
				return -1;
			}
			if(ErpcProtocolType.STRING.equals(input.getErpcType().getProtocolType())){
				limit++;
			}
			return  limit;
		}
		return -1;
	}

}
